using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.Domain.ExpandEntity.SystemLogs;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using SmartLink.EnumLibrary;

namespace SmartLink.Repository
{
    public class SYS_UserLoadingRepo : RepositoryBase<SYS_UserLoading>, ISYS_UserLoadingRepo
    {
        public IEnumerable<UserLoadingExpand> GetLoadingLogs(string keyValue, int clientType, IList<int> deptIds, int pageIndex, int pageSize, bool isSearchCount, out int count)
        {
            var selectSql = $@" SELECT su.NickName, bo.OrganizationShorterName OrganizeName, bod.DepartmentName, sul.* ";
            var fromSql = @" FROM sys_userloading sul
                        INNER JOIN sys_user su ON su.ID = sul.LoadingUserID
                        INNER JOIN biz_usertoorganization buo ON buo.UserID = su.ID
                        INNER JOIN biz_organization bo ON bo.ID = buo.OID
                        INNER JOIN biz_organizationdepartment bod ON bod.ID = buo.OD_ID ";
            var whereSql = $" WHERE su.IsDel<>1 AND bod.ID IN ({string.Join(",", deptIds)}) ";
            var orderSql = " ORDER BY sul.LoadingTime DESC ";
            var limitSql = " LIMIT @PageIndex, @PageSize";

            if (!string.IsNullOrWhiteSpace(keyValue))
                whereSql += " AND (su.NickName like @KeyValue OR su.AccountName like @KeyValue) ";
            if (clientType > 0)
                whereSql += $" AND sul.ClientType={clientType} ";

            pageIndex = (pageIndex - 1) * pageSize;
            var para = new { KeyValue = $"%{keyValue}%", PageIndex = pageIndex, PageSize = pageSize };
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var result = conn.Query<UserLoadingExpand>(selectSql + fromSql + whereSql + orderSql + limitSql, para);
                count = 0;
                if (isSearchCount)
                {
                    count = conn.ExecuteScalar<int>("SELECT COUNT(1) " + fromSql + whereSql, para);
                }
                return result;
            }
        }
    }
}
